<template>
  <view class="container">
    <!-- Form Section -->
    <view class="form-section">
      <view class="title">申请开具相关证明</view>
      
      <!-- Basic Info -->
      <view class="form-group">
        <text class="label">申请人基本信息</text>
        <view class="form-row">
          <text class="form-label">姓名：</text>
          <input v-model="form.name" placeholder="请输入姓名" class="input" />
          <text class="form-label">性别：</text>
          <input v-model="form.gender" placeholder="请输入性别" class="input" />
        </view>
        <view class="form-row">
          <text class="form-label">民族：</text>
          <input v-model="form.nation" placeholder="请输入民族" class="input" />
          <text class="form-label">身份证号：</text>
          <input v-model="form.idNumber" placeholder="请输入身份证号" class="input" />
        </view>
      </view>
      
      <!-- Police Station -->
      <view class="form-group">
        <text class="label">户籍地派出所</text>
        <input v-model="form.policeStation" placeholder="请输入派出所名称" class="full-input" />
      </view>
      
      <!-- Photo Uploads -->
      <view class="form-group">
        <text class="label">本人正面照片</text>
        <view class="upload-box" @click="uploadPhoto('face')">
          <image v-if="form.facePhoto" :src="form.facePhoto" class="photo"></image>
          <text v-else class="upload-text">点击上传正面照片</text>
        </view>
      </view>
      
      <view class="form-group">
        <text class="label">身份证正反面照片</text>
        <view class="upload-box" @click="uploadPhoto('idCard')">
          <image v-if="form.idCardPhoto" :src="form.idCardPhoto" class="photo"></image>
          <text v-else class="upload-text">点击上传身份证照片</text>
        </view>
      </view>
      
      <!-- Submit Button -->
      <button type="primary" @click="generateProof" class="submit-btn">生成证明</button>
    </view>
    
    <!-- Canvas for Proof Generation (hidden) -->
    <canvas canvas-id="proofCanvas" class="proof-canvas" :style="{width: canvasWidth+'px', height: canvasHeight+'px'}"></canvas>
    
    <!-- Preview and Download -->
    <view v-if="proofImage" class="preview-section">
      <view class="preview-title">证明预览</view>
      <image :src="proofImage" mode="widthFix" class="preview-image"></image>
      <button @click="downloadProof" class="download-btn">下载证明</button>
    </view>
  </view>
</template>

<script>
export default {
  data() {
    return {
      form: {
        name: '李会会',
        gender: '男',
        nation: '蒙古族',
        idNumber: '620524199712201463',
        policeStation: '测试部门2',
        facePhoto: '',
        idCardPhoto: ''
      },
      canvasWidth: 600,
      canvasHeight: 800,
      proofImage: '',
      serialNumber: '0000' // 编号
    }
  },
  methods: {
    uploadPhoto(type) {
      uni.chooseImage({
        count: 1,
        sizeType: ['compressed'],
        sourceType: ['album'],
        success: (res) => {
          if (type === 'face') {
            this.form.facePhoto = res.tempFilePaths[0]
          } else {
            this.form.idCardPhoto = res.tempFilePaths[0]
          }
        }
      })
    },
    generateProof() {
      if (!this.form.name || !this.form.idNumber || !this.form.policeStation) {
        uni.showToast({
          title: '请填写完整信息',
          icon: 'none'
        })
        return
      }
      
      uni.showLoading({
        title: '正在生成证明...'
      })
      
      const ctx = uni.createCanvasContext('proofCanvas', this)
      
      // 设置背景色
      ctx.setFillStyle('#ffffff')
      ctx.fillRect(0, 0, this.canvasWidth, this.canvasHeight)
      
      // 标题
      ctx.setFontSize(22)
      ctx.setFillStyle('#000000')
      ctx.setTextAlign('center')
      ctx.fillText('申请开具相关证明', this.canvasWidth/2, 50)
      
      // 编号
      ctx.setFontSize(14)
      ctx.setTextAlign('right')
      ctx.fillText(`编号：${this.serialNumber}`, this.canvasWidth-40, 80)
      
      // 基本信息表格
      this.drawTable(ctx)
      
      // 照片区域
      this.drawPhotos(ctx)
      
      // 承诺书
      this.drawCommitment(ctx)
      
      // 绘制
      ctx.draw(false, () => {
        setTimeout(() => {
          this.canvasToTempFilePath()
        }, 300)
      })
    },
    drawTable(ctx) {
      const startY = 100
      const lineHeight = 30
      const col1Width = 120
      const col2Width = 100
      const col3Width = 120
      const col4Width = 150
      
      // 表头
      ctx.setFontSize(16)
      ctx.setFillStyle('#000000')
      ctx.setTextAlign('left')
      ctx.fillText('申请人基本信息', 40, startY)
      
      // 表格线
      ctx.setStrokeStyle('#000000')
      ctx.setLineWidth(1)
      
      // 第一行
      ctx.fillText('姓名', 40, startY + lineHeight)
      ctx.fillText(this.form.name, 40 + col1Width, startY + lineHeight)
      ctx.fillText('性别', 40 + col1Width + col2Width, startY + lineHeight)
      ctx.fillText(this.form.gender, 40 + col1Width + col2Width + col3Width, startY + lineHeight)
      
      // 第二行
      ctx.fillText('民族', 40, startY + lineHeight * 2)
      ctx.fillText(this.form.nation, 40 + col1Width, startY + lineHeight * 2)
      ctx.fillText('身份证号', 40 + col1Width + col2Width, startY + lineHeight * 2)
      ctx.fillText(this.form.idNumber, 40 + col1Width + col2Width + col3Width, startY + lineHeight * 2)
      
      // 派出所信息
      ctx.fillText('户籍地派出所', 40, startY + lineHeight * 4)
      ctx.fillText(this.form.policeStation, 40 + col1Width, startY + lineHeight * 4)
      
      // 绘制表格线
      // 外框
      ctx.rect(35, startY - 20, this.canvasWidth - 70, lineHeight * 3 + 30)
      // 横线
      ctx.moveTo(35, startY + 10)
      ctx.lineTo(this.canvasWidth - 35, startY + 10)
      ctx.moveTo(35, startY + lineHeight + 20)
      ctx.lineTo(this.canvasWidth - 35, startY + lineHeight + 20)
      ctx.moveTo(35, startY + lineHeight * 2 + 20)
      ctx.lineTo(this.canvasWidth - 35, startY + lineHeight * 2 + 20)
      // 竖线
      ctx.moveTo(35 + col1Width, startY + 10)
      ctx.lineTo(35 + col1Width, startY + lineHeight * 2 + 20)
      ctx.moveTo(35 + col1Width + col2Width, startY + 10)
      ctx.lineTo(35 + col1Width + col2Width, startY + lineHeight * 2 + 20)
      ctx.moveTo(35 + col1Width + col2Width + col3Width, startY + 10)
      ctx.lineTo(35 + col1Width + col2Width + col3Width, startY + lineHeight * 2 + 20)
      
      ctx.stroke()
    },
    drawPhotos(ctx) {
      const startY = 280
      
      ctx.setFontSize(16)
      ctx.fillText('开具证明内容', 40, startY)
      
      // 照片标题
      ctx.fillText('本人正面照片', 40, startY + 40)
      ctx.fillText('身份证正反面照片', this.canvasWidth/2 + 20, startY + 40)
      
      // 照片框
      ctx.setStrokeStyle('#888888')
      ctx.setLineWidth(1)
      ctx.rect(40, startY + 50, 150, 180)
      ctx.rect(this.canvasWidth/2 + 20, startY + 50, 200, 120)
      ctx.stroke()
      
      // 绘制照片
      if (this.form.facePhoto) {
        ctx.drawImage(this.form.facePhoto, 45, startY + 55, 140, 170)
      }
      
      if (this.form.idCardPhoto) {
        ctx.drawImage(this.form.idCardPhoto, this.canvasWidth/2 + 25, startY + 55, 190, 110)
      }
    },
    drawCommitment(ctx) {
      const startY = 500
      
      ctx.setFontSize(16)
      ctx.fillText('承诺书', 40, startY)
      
      ctx.setFontSize(14)
      const text = '本人提供的身份证信息及佐证材料真实、完整、有效，没有任何虚假、伪造、变造、冒用等行为。均系真实情况。'
      this.wrapText(ctx, text, 40, startY + 30, this.canvasWidth - 80, 24)
      
      // 时间
      const date = new Date()
      const dateStr = `${date.getFullYear()}-${this.padZero(date.getMonth()+1)}-${this.padZero(date.getDate())} ${this.padZero(date.getHours())}:${this.padZero(date.getMinutes())}:${this.padZero(date.getSeconds())}`
      
      ctx.setTextAlign('right')
      ctx.fillText(`时间：${dateStr}`, this.canvasWidth - 40, startY + 120)
    },
    wrapText(ctx, text, x, y, maxWidth, lineHeight) {
      const words = text.split('')
      let line = ''
      let testLine = ''
      let lineArray = []
      
      for(let n = 0; n < words.length; n++) {
        testLine = line + words[n]
        const metrics = ctx.measureText(testLine)
        const testWidth = metrics.width
        
        if (testWidth > maxWidth && n > 0) {
          lineArray.push(line)
          line = words[n]
        } else {
          line = testLine
        }
      }
      
      lineArray.push(line)
      
      for(let m = 0; m < lineArray.length; m++) {
        ctx.fillText(lineArray[m], x, y)
        y += lineHeight
      }
    },
    padZero(num) {
      return num < 10 ? '0' + num : num
    },
    canvasToTempFilePath() {
      uni.canvasToTempFilePath({
        canvasId: 'proofCanvas',
        success: (res) => {
          this.proofImage = res.tempFilePath
          uni.hideLoading()
          uni.showToast({
            title: '证明生成成功',
            icon: 'success'
          })
          
          // 自动滚动到预览区域
          uni.pageScrollTo({
            scrollTop: 1000,
            duration: 300
          })
        },
        fail: (err) => {
          console.error(err)
          uni.hideLoading()
          uni.showToast({
            title: '生成失败',
            icon: 'none'
          })
        }
      }, this)
    },
    downloadProof() {
      uni.showLoading({
        title: '正在保存...'
      })
      
      uni.saveImageToPhotosAlbum({
        filePath: this.proofImage,
        success: () => {
          uni.hideLoading()
          uni.showToast({
            title: '保存成功',
            icon: 'success'
          })
        },
        fail: (err) => {
          console.error(err)
          uni.hideLoading()
          uni.showToast({
            title: '保存失败',
            icon: 'none'
          })
        }
      })
    }
  }
}
</script>

<style>
.container {
  padding: 20rpx;
  background-color: #f5f5f5;
  min-height: 100vh;
}

.title {
  font-size: 36rpx;
  font-weight: bold;
  text-align: center;
  margin: 20rpx 0 40rpx;
}

.form-section {
  background-color: #fff;
  padding: 30rpx;
  border-radius: 10rpx;
  margin-bottom: 20rpx;
}

.form-group {
  margin-bottom: 40rpx;
}

.label {
  display: block;
  font-weight: bold;
  margin-bottom: 20rpx;
  font-size: 32rpx;
}

.form-row {
  display: flex;
  flex-wrap: wrap;
  align-items: center;
  margin-bottom: 20rpx;
}

.form-label {
  width: 120rpx;
  font-size: 28rpx;
}

.input {
  flex: 1;
  padding: 15rpx;
  border: 1rpx solid #ddd;
  border-radius: 8rpx;
  margin: 5rpx;
  min-width: 150rpx;
}

.full-input {
  width: 100%;
  padding: 15rpx;
  border: 1rpx solid #ddd;
  border-radius: 8rpx;
}

.upload-box {
  height: 200rpx;
  border: 1rpx dashed #ccc;
  display: flex;
  justify-content: center;
  align-items: center;
  color: #888;
}

.upload-text {
  font-size: 28rpx;
  color: #666;
}

.photo {
  width: 100%;
  height: 100%;
}

.submit-btn {
  margin-top: 40rpx;
  background-color: #007AFF;
  color: white;
}

.proof-canvas {
  position: fixed;
  left: -9999rpx;
}

.preview-section {
  background-color: #fff;
  padding: 30rpx;
  border-radius: 10rpx;
  margin-top: 30rpx;
}

.preview-title {
  font-size: 32rpx;
  font-weight: bold;
  margin-bottom: 20rpx;
  text-align: center;
}

.preview-image {
  width: 100%;
  margin-bottom: 30rpx;
  border: 1rpx solid #eee;
}

.download-btn {
  background-color: #4CAF50;
  color: white;
}
</style>